<?php
require_once('connect.php');

function getConnection()
{
    $mysql = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if($mysql->connect_error)
        die('Connection error: '.$mysql->connect_error);
    
    return $mysql;
}

function getAllTables()
{
    $conn = getConnection();
    $result = $conn->query('SHOW TABLES');
    $conn->close();
    
    return $result;
}

function getTable($table)
{
    $conn = getConnection();
    $result = $conn->query("SELECT * FROM $table");
    $conn->close();
    
    return $result;
}

function getAllUsers()
{
    $conn = getConnection();
    $result = $conn->query('SELECT * FROM users');
    $conn->close();
    
    return $result;
}

function getUser($id)
{
    $conn = getConnection();
    $result = $conn->query("SELECT * FROM users WHERE id='$id'");
    $rs = $result->fetch_assoc();
    $conn->close();
    
    return $rs;
}

function insertUser($post)
{
    $form = array();
    foreach($post as $data)
    {
        $data = htmlspecialchars(trim($data));
        strlen($data) == 0 ? $form[] = NULL : $form[] = $data;
    }
    
    if($form[1] == NULL)
        $q = "INSERT INTO users (created, first_name, middle_initial, last_name, email, password, billing_id, shipping_id) VALUES(NOW(), '$form[0]', NULL, '$form[2]', '$form[3]', '$form[4]', '$form[5]', '$form[6]')";

    else
        $q = "INSERT INTO users (created, first_name, middle_initial, last_name, email, password, billing_id, shipping_id) VALUES(NOW(), '$form[0]', '$form[1]', '$form[2]', '$form[3]', '$form[4]', '$form[5]', '$form[6]')";
    
    $conn = getConnection();
    $conn->query($q);
    $conn->close();
}

?>
